package com.rc.saas.tenant.init;

import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantExample;
import com.rc.saas.tenant.service.tenant.TenantService;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 启动时初始化
 * Created by Sven on 2021/04/07
 */
//@Component
public class TenantApplicationRunner implements ApplicationRunner {
    private static Logger logger = LogManager.getLogger(TenantApplicationRunner.class);

    @Autowired
    private TenantService tenantService;

    @Autowired
    private RedisTenantConfigurationLoader redisAppConfigurationLoader;

    @Override
    public void run(ApplicationArguments args) {
        logger.info("-------------- 开始加载APP配置信息 ---------------------------");

        List<Tenant> list = tenantService.selectByExample(new TenantExample());
        for (Tenant tenant : list) {
            if (StringUtils.isNotBlank(tenant.getTenantCode())) {
                //初始化配置类
                RedisTenantConfig redisAppConfig = new RedisTenantConfig(tenant.getTenantCode(),
                        tenant.getTenantName(), tenant.getTenantPrefix(), tenant.getTenantLogoImg());

                //将配置类保存到Redis缓存中,有效期365天
                redisAppConfigurationLoader.set(redisAppConfig);
                logger.info("将APP配置信息保存到Redis缓存中:{}", redisAppConfig);
            }
        }
    }
}
